package com.shlh.saas.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shlh.saas.entity.EmailPackage;
import com.shlh.saas.entity.EmailSendRecord;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.mapper.EmailPackageMapper;
import com.shlh.saas.mapper.EmailSendRecordMapper;
import com.shlh.saas.service.EmailPackageService;
import com.shlh.saas.service.RechargeRecordService;
import com.shlh.saas.service.UserBalanceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 邮件套餐服务实现类
 */
@Service
public class EmailPackageServiceImpl implements EmailPackageService {

    private static final Logger log = LoggerFactory.getLogger(EmailPackageServiceImpl.class);

    @Autowired
    private EmailPackageMapper emailPackageMapper;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private RechargeRecordService rechargeRecordService;
    
    @Autowired
    private EmailSendRecordMapper emailSendRecordMapper;

    @Override
    public List<EmailPackage> getAllValidPackages() {
        log.info("开始获取所有有效的邮件套餐列表");
        try {
            List<EmailPackage> packages = emailPackageMapper.selectAllValidPackages();
            log.info("成功获取邮件套餐列表，共{}个套餐", packages != null ? packages.size() : 0);
            return packages;
        } catch (Exception e) {
            log.error("获取邮件套餐列表时发生异常: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public EmailPackage getPackageById(Long id) {
        log.info("开始获取ID为{}的邮件套餐", id);
        try {
            EmailPackage emailPackage = emailPackageMapper.selectById(id);
            log.info("成功获取ID为{}的邮件套餐: {}", id, emailPackage != null ? emailPackage.getName() : "未找到");
            return emailPackage;
        } catch (Exception e) {
            log.error("获取ID为{}的邮件套餐时发生异常: {}", id, e.getMessage(), e);
            return null;
        }
    }

    @Override
    @Transactional
    public boolean purchaseEmailPackage(String phone, Long packageId) {
        log.info("用户{}开始购买ID为{}的邮件套餐", phone, packageId);
        try {
            // 1. 获取邮件套餐信息
            EmailPackage emailPackage = emailPackageMapper.selectById(packageId);
            if (emailPackage == null || emailPackage.getIsDeleted() == 1) {
                log.warn("用户{}尝试购买的邮件套餐ID{}不存在或已被删除", phone, packageId);
                return false;
            }
            log.info("用户{}购买的邮件套餐信息: 名称={}, 邮件数量={}, 价格={}", 
                    phone, emailPackage.getName(), emailPackage.getEmailCount(), emailPackage.getPrice());
            
            // 2. 增加用户邮件配额
            boolean quotaResult = userBalanceService.increaseEmailQuota(phone, emailPackage.getEmailCount());
            
            // 3. 更新用户邮件套餐等级
            // 根据套餐ID或名称确定套餐等级
            Integer packageLevel = 0;
            if (emailPackage.getName().contains("A") || emailPackage.getName().contains("基础")) {
                packageLevel = 1;
            } else if (emailPackage.getName().contains("B") || emailPackage.getName().contains("进阶")) {
                packageLevel = 2;
            } else if (emailPackage.getName().contains("C") || emailPackage.getName().contains("高级")) {
                packageLevel = 3;
            } else if (emailPackage.getName().contains("D") || emailPackage.getName().contains("尊享")) {
                packageLevel = 4;
            }
            
            log.info("用户{}购买邮件套餐，设置套餐等级为{}", phone, packageLevel);
            boolean levelResult = userBalanceService.updateEmailPackageLevel(phone, packageLevel);
            
            // 4. 创建交易记录
            if (quotaResult && levelResult) {
                // 获取用户当前余额
                UserBalance userBalance = userBalanceService.getUserBalance(phone);
                BigDecimal afterAmount = userBalance != null ? userBalance.getCashBalance() : new BigDecimal("0.00");
                
                // 创建消费记录
                String description = "购买" + emailPackage.getName() + "套餐";
                
                // 设置配额增量（邮件数量）
                Integer quotaAdded = emailPackage.getEmailCount();
                
                log.info("创建邮件套餐充值记录 - 套餐ID: {}, 邮件数量: {}, 描述: {}", packageId, quotaAdded, description);
                
                boolean recordCreated = rechargeRecordService.createRecord(
                    phone,
                    "EMAIL", // 使用EMAIL类型
                    emailPackage.getPrice(), // 使用套餐价格
                    afterAmount,
                    description,
                    "alipay", // 默认支付宝支付
                    packageId.intValue() // 确保传递正确的packageId
                );
                
                log.info("用户{}购买邮件套餐交易记录创建结果: {}", phone, recordCreated ? "成功" : "失败");
            }
            
            boolean result = quotaResult && levelResult;
            log.info("用户{}购买邮件套餐结果: {}", phone, result ? "成功" : "失败");
            return result;
        } catch (Exception e) {
            log.error("用户{}购买ID为{}的邮件套餐时发生异常: {}", phone, packageId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Map<String, Object> getEmailSendRecords(String phone, Integer page, Integer size) {
        log.info("获取用户{}的邮件发送记录，页码：{}，每页大小：{}", phone, page, size);
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建分页对象
            Page<EmailSendRecord> pageParam = new Page<>(page, size);
            
            // 查询分页数据
            Page<EmailSendRecord> recordPage = emailSendRecordMapper.selectPageByPhone(pageParam, phone);
            
            // 获取统计数据
            int totalSent = emailSendRecordMapper.countByPhone(phone);
            int totalDelivered = emailSendRecordMapper.sumDeliveryCountByPhone(phone);
            int totalRead = emailSendRecordMapper.sumReadCountByPhone(phone);
            
            // 组装返回数据
            result.put("records", recordPage.getRecords());
            result.put("total", recordPage.getTotal());
            result.put("pages", recordPage.getPages());
            result.put("current", recordPage.getCurrent());
            result.put("size", recordPage.getSize());
            
            // 添加统计数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalSent", totalSent);
            stats.put("totalDelivered", totalDelivered);
            stats.put("totalRead", totalRead);
            
            // 计算送达率和阅读率
            double deliveryRate = totalSent > 0 ? (double) totalDelivered / totalSent * 100 : 0;
            double readRate = totalDelivered > 0 ? (double) totalRead / totalDelivered * 100 : 0;
            stats.put("deliveryRate", String.format("%.2f", deliveryRate) + "%");
            stats.put("readRate", String.format("%.2f", readRate) + "%");
            
            result.put("stats", stats);
            
            log.info("成功获取用户{}的邮件发送记录，共{}条", phone, recordPage.getTotal());
            return result;
        } catch (Exception e) {
            log.error("获取用户{}的邮件发送记录时发生异常: {}", phone, e.getMessage(), e);
            
            // 出错时返回空数据
            result.put("records", List.of());
            result.put("total", 0);
            result.put("pages", 0);
            result.put("current", page);
            result.put("size", size);
            result.put("stats", Map.of(
                "totalSent", 0,
                "totalDelivered", 0,
                "totalRead", 0,
                "deliveryRate", "0.00%",
                "readRate", "0.00%"
            ));
            
            return result;
        }
    }
} 